package utils;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;

/**
 * 自定义连接池：用于复用连接
 */

public class DBConnectionPool implements DataSource {

    private static LinkedList<Connection> coonPool = new LinkedList<>();
    private static final int COONPOOL_MIN_SIZE = 5;

    static {
        for (int i = 0; i < COONPOOL_MIN_SIZE; i++) {
            Connection connection = JdbcUtil.getConnectionDB();
            coonPool.add(connection);
        }
    }

    /**
     * 从连接池中获取连接
     *
     * @return
     * @throws SQLException
     */
    @Override
    public Connection getConnection() throws SQLException {
        //判断连接池中连接数，为0时就创建5个
        if (coonPool.size() == 0) {
            for (int i = 0; i < COONPOOL_MIN_SIZE; i++) {
                Connection connection = JdbcUtil.getConnectionDB();
                coonPool.add(connection);
            }
        }
        return coonPool.removeFirst();
    }

    /**
     * 向连接池归还连接
     *
     * @param connection
     */
    public void returnBackCoonToPool(Connection connection) {
        coonPool.add(connection);
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
